﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using UnityEngine.UI;
using UnityEngine.Events;

public class Joy : MonoBehaviour {
    public GameObject bgGo;
    public GameObject joyGo;
    public float offsetMax = 100.0f;
    Vector3 startPos = Vector3.zero;
    public float ctrlTimes = 20.0f;

    public class OnJoyBegainHandle : UnityEvent { };
    public class OnJoyMoveHandle : UnityEvent<Vector3> { };

    public OnJoyBegainHandle onJoyBegain = new OnJoyBegainHandle();
    public OnJoyMoveHandle onJoyMove = new OnJoyMoveHandle();

	// Use this for initialization
	void Start () {
		
	}
	
	// Update is called once per frame
	void Update () {
        if (Input.GetMouseButtonDown(0)) {
            startPos = Input.mousePosition;
            bgGo.GetComponent<RectTransform>().anchoredPosition3D = Input.mousePosition - new Vector3(1080.0f/2,1920.0f/2,0);
            onJoyBegain.Invoke();
        }
        if (Input.GetMouseButton(0)){
            Vector3 detlaPos = Input.mousePosition - startPos;
            if (Vector3.Distance(detlaPos, Vector3.zero) > offsetMax) {
                detlaPos = detlaPos / Vector3.Distance(detlaPos, Vector3.zero) * offsetMax;
            }
            joyGo.GetComponent<RectTransform>().anchoredPosition3D = detlaPos;
            detlaPos *= ctrlTimes;
            onJoyMove.Invoke(detlaPos);
        }
        if (Input.GetMouseButtonUp(0)){
            startPos = Vector3.zero;
            bgGo.GetComponent<RectTransform>().anchoredPosition3D = new Vector3(-330.0f,-758.0f,0);
            joyGo.GetComponent<RectTransform>().anchoredPosition3D = Vector3.zero;
        }
	}
}
